package com.team.instantsharing.user

import java.nio.charset.Charset;
import java.text.DecimalFormat
import java.util.List;

import com.team.instantsharing.dto.Document;
import com.team.instantsharing.dto.LoginResponse;
import com.team.instantsharing.dto.Message
import com.team.instantsharing.dto.User;
import com.team.instantsharing.dto.UserChangePwd;
import com.team.instantsharing.ultils.Constant;
import com.team.instantsharing.ultils.FileConvert;
import com.team.instantsharing.ultils.Password;
import com.team.instantsharing.ultils.RequestHeader;
import com.team.instantsharing.ultils.ServiceRequest;

import grails.converters.JSON
import grails.plugin.cookie.CookieService;

import org.codehaus.groovy.grails.web.json.JSONObject
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate

class UserController {

	CookieService cookieService;
	
	def login() {
		boolean isRemember = false;
		if (params.remember != null && params.remember.equals("true")){
			isRemember = true;
		}
		User user = new User();
		user.setUserEmail(params.userEmail);
		user.setPassword(params.password);
		user.setPlatForm("WEB");
		if (isRemember == true){
			user.setRememberToken(session.getId());
		}
		user.setRemember(isRemember);
		
		RestTemplate restTemplate = new RestTemplate();
		HttpEntity<User> userEntity = new HttpEntity<User>(user, RequestHeader.getDefaultHeader());
		LoginResponse loginResponse = restTemplate.exchange(Constant.SERVICE_URL + ServiceRequest.LOGIN, HttpMethod.POST, userEntity, LoginResponse.class).body;

		def returnMessage;
		if (loginResponse.getUserId() > 0){
			returnMessage = "Successful"
			//Put Session
			session.userName = loginResponse.getUserName()
			session.userId = loginResponse.getUserId()
			session.userToken = loginResponse.getUserToken();
			session.userEmail = user.getUserEmail()
			session.availableCapacity = loginResponse.getAvailableCapacity();
			session.usedCapacity = loginResponse.getUsedCapacity();
			session.availableCapacityString = FileConvert.getDocumentCapacityString(loginResponse.getAvailableCapacity());
			session.usedCapacityString = FileConvert.getDocumentCapacityString(loginResponse.getUsedCapacity());
			if (isRemember == true){
				cookieService.setCookie('remember_me_cookie', user.getRememberToken())
			}
		}
		else if (loginResponse.getUserId() == Constant.WRONG_PASSWORD){
			returnMessage = "Login failed! Incorrect password."
		}
		else if (loginResponse.getUserId() == Constant.NOT_ACTIVATE){
			StringBuffer stringReturn = new StringBuffer("This email was registered but not yet activated. ");
			stringReturn.append("<span id='user-activation-renew' onclick='resendActivationLink()'><u>Resend the activation email</u>");
			stringReturn.append('<span class="hidden" id="user-acitvation-renew-email">');
			stringReturn.append(user.getUserEmail());
			stringReturn.append('</span>');
			stringReturn.append('</span>');

			returnMessage = stringReturn.toString();
		}
		else{
			returnMessage = "This email is not registered"
		}

		render ([info:returnMessage] as JSON)
	}
	
	def register() {
		User user = new User();
		user.setUserEmail(params.registerEmail);
		user.setUserName(params.registerName);
		user.setPassword(params.registerPassword);
		user.setActivated(false);

		RestTemplate restTemplate = new RestTemplate();
		HttpEntity<User> userEntity = new HttpEntity<User>(user, RequestHeader.getDefaultHeader());
		Message registerResponse = restTemplate.exchange(Constant.SERVICE_URL + ServiceRequest.REGISTER, HttpMethod.POST, userEntity, Message.class).body;

//		Message registerResponse = new Message(Constant.REGISTER_SUCCESS);
		flash.user_register_msg = registerResponse.response;
		redirect controller: 'home', action: 'index';
	}
	
	def registerConfirm() {
		RestTemplate restTemplate = new RestTemplate();
		HttpEntity entity = new HttpEntity(RequestHeader.getDefaultHeader());
		Message statusConfirm = restTemplate.exchange(Constant.SERVICE_URL + ServiceRequest.REGISTER_CONFIRM + "?userEmail=" + params.userEmail + "&activationCode=" + params.activationCode, HttpMethod.GET, entity, Message.class).body;
//		Message statusConfirm = new Message(Constant.ACTIVATE_SUCCESS);
		if (statusConfirm.response.equals("Expired activation link")){
			session.emailResend = params.userEmail;
		}
		flash.user_register_confirm_msg = statusConfirm.response;
		redirect controller:'home', action: 'index';
	}

	def reSendActivationLink() {
		RestTemplate restTemplate = new RestTemplate();
		HttpEntity entity = new HttpEntity(RequestHeader.getDefaultHeader());
		Message resendActivateResponse = restTemplate.exchange(Constant.SERVICE_URL + ServiceRequest.RESEND_ACTIVATION_LINK + "?userEmail=" + params.userEmail, HttpMethod.GET, entity, Message.class).body;
		if (resendActivateResponse.response.equals("true")){
			flash.user_register_msg = "Register successfully";
		}
		render ([info:resendActivateResponse.response] as JSON)
	}

	def forgetPassword() {
		String forgotEmail = params.forgotEmail;
		RestTemplate restTemplate = new RestTemplate();
		HttpEntity entity = new HttpEntity(RequestHeader.getDefaultHeader());
		Message checkEmailMessage = restTemplate.exchange(Constant.SERVICE_URL + ServiceRequest.CHECK_EMAIL_EXIST + "?userEmail=" + forgotEmail, HttpMethod.GET, entity, Message.class).body;
//		Message checkEmailMessage = new Message("false");
		if (checkEmailMessage.response.equals("false")) {
			render ([info:"Email is not exist"] as JSON)
		}
		else{
			RestTemplate restTemplateNew = new RestTemplate();
			Message statusForgot = restTemplateNew.exchange(Constant.SERVICE_URL+ ServiceRequest.FORGET_PASSWORD + "?userEmail=" + forgotEmail, HttpMethod.GET, entity, Message.class).body;
//			Message statusForgot = new Message(Constant.EMAIL_NOT_EXIST);
			if (statusForgot.response.equals(Constant.SEND_EMAIL_FORGET_SUCCESS)){
				flash.user_forgot_msg = Constant.SEND_EMAIL_FORGET_SUCCESS;
			}
			render ([info:statusForgot.response] as JSON)
		}
	}

	def resetPassword() {
		String key = params.key;
		String[] keySplit = null;
		boolean isError = false;
		if (key == null || key == ""){
			isError = true;
		}
		else{
			keySplit = key.split("@");
			if (keySplit.length < 2){
				isError = true;
			}
		}
		if (isError == true){
			render "view":"/errorPage/error404.gsp"
			return;
		}
		[userId: keySplit[0], keyResetPass: keySplit[1]]
	}

	def changePassword(){
		User user = new User();
		user.setUserId(Long.parseLong(params.userId));
		user.setPassword(params.keyResetPass);
		UserChangePwd userChangePwd = new UserChangePwd(user, params.newPassword);
		RestTemplate restTemplateNew = new RestTemplate();
		HttpEntity<User> userChangePwdEntity = new HttpEntity<User>(userChangePwd, RequestHeader.getDefaultHeader());
		Message statusChangePwd = restTemplateNew.exchange(Constant.SERVICE_URL+ ServiceRequest.CHANGE_PASSWORD + Constant.SUFFIX + params.keyResetPass, HttpMethod.POST, userChangePwdEntity, Message.class).body;
//		Message statusChangePwd = new Message(Constant.CHANGE_PASSWORD_SUCCESS);
		flash.change_password_msg = statusChangePwd.response;
		redirect controller: 'home', action: 'index';
	}
	
	def checkUserEmailExist(){
		String registerEmail = params.registerEmail; 
		RestTemplate restTemplate = new RestTemplate();
		HttpEntity entity = new HttpEntity(RequestHeader.getDefaultHeader());
		Message checkEmailMessage = restTemplate.exchange(Constant.SERVICE_URL + ServiceRequest.CHECK_EMAIL_EXIST + "?userEmail=" + registerEmail,HttpMethod.GET, entity, Message.class).body;
		boolean checkEmailBoolean = Boolean.parseBoolean(checkEmailMessage.response);
		render new JSONObject().put("valid", !checkEmailBoolean);
	}
	
	def logOut(){
		session.userName = null;
		session.userId = null;
		session.userToken = null;
		session.userPicture = null;
		session.userEmail = null;
		cookieService.setCookie('remember_me_cookie', "");
		session.removeValue("facebook:oasAccessToken");
		session.removeValue("google:oasAccessToken");
		redirect controller: 'home', action: 'index';
	}
}
